<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/06/10
// +----------------------------------------------------------------------
namespace app\erp\logic;
use app\erp\model\ErpAllocation;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
/**
 * 调拨管理
 * @package app\erp\model
 */
class Allocationlogic{

    /**
     * 首页
     * @author  dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function index($user_id, $code, $from_warehouse_id, $to_warehouse_id, $handled_by,$all_status=''){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' => $user_id,
            ];
            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $map = [];//搜索处理
            if($user_id != '')          $map[] = ['uid', 'like', '%'. $user_id .'%'];
            if($from_warehouse_id > 0) 	$map[] = ['from_warehouse_id', '=', $from_warehouse_id];
            if($to_warehouse_id > 0) 	$map[] = ['to_warehouse_id', '=', $to_warehouse_id];
            if($code != '') 			$map[] = ['code', 'like', '%'. $code .'%'];
            if($handled_by != '') 		$map[] = ['handled_by', 'like', '%'. $handled_by .'%'];
            if($all_status != '') 		$map[] = ['all_status', '=', $all_status];
			$list =  model('ErpAllocation', 'model') -> where($map) -> order('create_time desc') -> paginate();//获取列表
			$rel_list = [];
            foreach($list as $key => $value){
                $rel_list[$key]['allocation_id'] 			= (int)$value['id'];
                $rel_list[$key]['uid'] 			            = (int)$value['uid'];
                $rel_list[$key]['fromWarehouseId']          = (string)$value['from_warehouse_id'];
                $rel_list[$key]['fromWarehouseIdNick']      = (string)get_nick_name('1','ErpWarehouse','id',$value['from_warehouse_id'],'title');
                $rel_list[$key]['toWarehouseId'] 	        = (string)$value['to_warehouse_id'];
                $rel_list[$key]['toWarehouseIdNick'] 	    = (string)get_nick_name('1','ErpWarehouse','id',$value['to_warehouse_id'],'title');
                $rel_list[$key]['remark'] 		            = (string)$value['remark'];
                $rel_list[$key]['code'] 		            = (string)$value['code'];
                $rel_list[$key]['handledBy']                = (string)$value['handled_by'];
                $rel_list[$key]['createTime']               = (string)$value['create_time'];
                $rel_list[$key]['updateTime']               = (string)$value['update_time'];
                //查询sku表
                $sku = model('ErpAllocationSku') -> where(['allocation_id'=>$value['id']])->select()->toArray();
                $rel_list[$key]['sku']['id']                = $sku[0]['id'];
                $rel_list[$key]['sku']['allocationId']      = $sku[0]['allocation_id'];
                $rel_list[$key]['sku']['skuId']             = $sku[0]['sku_id'];
                $rel_list[$key]['sku']['num']               = $sku[0]['num'];
                $rel_list[$key]['sku']['createTime']        = $sku[0]['create_time'];
                $rel_list[$key]['sku']['updateTime']        = $sku[0]['update_time'];
			}
            $result_list = [];
            $result_list['total']  			= (int)$list -> total();//总数
            $result_list['current_page']	= (int)$list -> currentPage();//页码
            $result_list['last_page']   	= (int)$list -> lastPage();//总页数
            $result_list['per_page']   		= (int)$list -> listRows();//每页条数
            $result_list['data'] 			= $rel_list;
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }


    /**
     * 添加
     * @param uid 	                    int         操作人
     * @param from_warehouse_id 		int         调出仓
     * @param to_warehouse_id 		    int
     * @param remarks 		            string      备注
     * @param handled_by 		        string      经办人
     * @param code 		                string      调拨单号
     * @param sku_id 		            int         单品id
     * @param num 		                int         单品数量
     * @param create_time 		        date
     * @param update_time 	            date
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function add($user_id, $from_warehouse_id, $to_warehouse_id, $remarks, $handled_by, $code, $sku){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	        => $user_id,
				'from_warehouse_id' => $from_warehouse_id,
				'to_warehouse_id'   => $to_warehouse_id,
                'remarks' 	        => $remarks,
                'handled_by'        => $handled_by,
                'code' 	            => $code,
                'sku' 	            => $sku
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            //货物数量校验-先更新再查
            foreach ($sku as $k => $v) {
                $rel_upnum = model('ErpGoodsWarehouseStockNum')->editDataForAllocation($from_warehouse_id, $v['sku_id'], $v['num']);
                if($rel_upnum['code'] == 200){
                    //更新完查询如果小于0 则回滚
                    $map_ishave = [];
                    if($from_warehouse_id > 0) 	$map_ishave[] = ['warehouse_id', '=', $from_warehouse_id];
                    if($v['sku_id'] > 0) 	    $map_ishave[] = ['sku_id', '=', $v['sku_id']];
                    $res_ishave = model('ErpGoodsWarehouseStockNum')->where($map_ishave)->find();//dump($res_ishave);
                    if($res_ishave['available_num'] <= 0){
                        DB::rollback();
                        return array_out(-1003, '暂时无货');//查询失败 返回-1003,error
                    }
                }else{
                    DB::rollback();
                    return array_out(-1005, '库存不足, SKU_id:'.$v['sku_id']);//添加失败 返回-1005,error
                }
            }

			$rel = model('ErpAllocation') -> addData($user_id, $from_warehouse_id, $to_warehouse_id, $remarks, $handled_by, $code);//添加
            if($rel['code'] == 200){
                $allocation_id = $rel['data'];
                foreach ($sku as $k => $v){
                    $rel = model('ErpAllocationSku') -> addData( $allocation_id, $v['sku_id'], $v['num']);//添加
                    if($rel['code'] < 0){
                        DB::rollback();
                        return array_out(-1003, $hook_rel['message']);//后置错误 -1003
                    }
                }
            }else{
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success',$rel['data']);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }


    /**
     * 出库操作
     */
    public function outGoing($user_id,$id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'user_id' 	        => $user_id,
                'id'                => $id,
            ];
            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            //更新allocation调拨状态 0申请中 1已审核 2已出库 3取消出库 4已入库
            $rel = model('ErpAllocation') -> editDataOutGoing($id,'2');
            if($rel['code'] == 200){
                $rel = model('ErpAllocation') -> outGoing($id);//出库减库存
                if($rel['code'] < 0){
                    DB::rollback();
                    return array_out(-1003, $hook_rel['message']);//后置错误 -1003
                }
            }else{
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
            DB::commit();
            return array_out(200, 'success',$rel['data']);
            /********逻辑返回********/

        } catch (\Exception $e) {
            DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

}